const express = require('express');
const mongo = require('../db/mongo')
const router = express.Router();

//获取文章列表
router.get('/', async (req, res) => {
    const { size, page, id } = req.query;
    console.log(id);
    let limit = Number(size);
    let skip = (page - 1) * size
    var data = await mongo.find('article', {}, { limit, skip })

    if (data) {
        res.send({
            code: 200,
            data,
            msg: '请求成功'
        })
    } else {
        res.send({
            code: 400,
            data: [],
            msg: '请求失败'
        })
    }

})


//获取单个文章
router.get('/:id', async (req, res) => {
    const { id } = req.params;
    // console.log('id=', id);
    var data = await mongo.find('article', { _id: id }, {})
    res.send({
        code: 200,
        data,
        msg: '请求成功'
    })
})



//增加文章

router.post('/', async (req, res) => {
    let date = new Date().toLocaleDateString()
    const config = req.body;
    config.date = date
    console.log(config);
    const data = await mongo.insert('article', config);
    if (data) {
        res.send({
            code: 200,
            msg: '添加成功'
        })
    } else {
        res.send({
            code: 400,
            msg: '添加失败'
        })
    }
})

//删除文章

router.delete('/', async (req, res) => {
    const config = req.body;
    console.log('config', config);
    const { result, num } = await mongo.remove('article', config);
    if (result && num == 0) {
        res.send({
            code: 300,
            msg: `未找到此文章`
        })
    } else if (result) {
        res.send({
            code: 200,
            msg: `成功删除${num}条数据`
        })
    }
    else {
        res.send({
            code: 400,
            msg: '删除失败'
        })
    }
})

// 修改文章
router.put('/:id', async (req, res) => {
    const { id } = req.params;
    const { title, descript, keyworks, tag, content } = req.body;
    // console.log('config', title, descript, keyworks, tag, content, id);
    const result = await mongo.updata('article', { _id: id }, {
        $set: {
            title,
            descript,
            keyworks,
            tag,
            content
        }
    });
    if (result) {
        res.send({
            code: 200,
            msg: '修改成功'
        })
    } else {
        res.send({
            code: 400,
            msg: '修改失败'
        })
    }
})

module.exports = router